"""
大麦网App抢票系统主控制器
整合所有模块，提供统一的抢票服务（移动端版本）
"""

import time
import logging
from typing import Dict, Any
from utils.airtest_driver import AirtestMobileDriver, AIRTEST_AVAILABLE
from utils.adb_driver import AdbMobileDriver  # ADB驱动器作为备选
from utils.config_manager import ConfigManager
from utils.common_utils import setup_logging, show_notification
from src.damai_login import DamaiLogin
from src.damai_ticket_selector import DamaiTicketSelector
from src.damai_ticket_grabber import DamaiTicketGrabber


class DamaiTicketController:
    """大麦网App抢票控制器"""

    def __init__(self, config_path: str = "config/config.json"):
        self.config_manager = ConfigManager(config_path)
        self.config: Dict[str, Any] = {}
        self.driver = None  # 移动端驱动器（将根据可用性选择）
        self.login_handler: DamaiLogin = None
        self.ticket_selector: DamaiTicketSelector = None
        self.ticket_grabber: DamaiTicketGrabber = None
        self.logger = None

    def initialize(self) -> bool:
        """初始化系统"""
        try:
            # 设置日志
            self.logger = setup_logging()
            self.logger.info("开始初始化App抢票系统")

            # 加载配置
            self.config = self.config_manager.load_config()
            self.logger.info("配置文件加载成功")

            # 初始化移动端驱动，优先使用Airtest，失败时使用ADB
            try:
                if AIRTEST_AVAILABLE:
                    self.driver = AirtestMobileDriver(self.config)
                    self.driver.init_device()
                    self.logger.info("使用Airtest驱动器")
                else:
                    raise Exception("Airtest不可用")
            except Exception as e:
                self.logger.warning(f"Airtest驱动器初始化失败: {e}")
                self.logger.info("正在切换到ADB驱动器...")
                try:
                    self.driver = AdbMobileDriver(self.config)
                    self.driver.init_device()
                    self.logger.info("使用ADB驱动器")
                except Exception as e2:
                    self.logger.error(f"ADB驱动器也初始化失败: {e2}")
                    raise e2

            # 初始化各个模块
            self.login_handler = DamaiLogin(self.driver, self.config)
            self.ticket_selector = DamaiTicketSelector(self.driver, self.config)
            self.ticket_grabber = DamaiTicketGrabber(self.driver, self.config)

            self.logger.info("系统初始化完成")
            return True

        except Exception as e:
            if self.logger:
                self.logger.error(f"系统初始化失败: {e}")
            else:
                print(f"系统初始化失败: {e}")
            return False

    def run_ticket_grabbing(self) -> bool:
        """执行完整的抢票流程"""
        try:
            self.logger.info("=" * 50)
            self.logger.info("开始执行大麦网App抢票流程")
            self.logger.info("=" * 50)

            ticket_config = self.config.get("ticket", {})
            event_name = ticket_config.get("event_name", "")
            event_url = ticket_config.get("event_url", "")

            if not event_name:
                self.logger.error("未配置演出名称")
                return False

            # 步骤1: 启动App并登录
            self.logger.info("步骤1: 启动App并检查登录状态")
            if not self.login_handler.is_logged_in():
                self.logger.info("需要登录，开始登录流程")
                if not self.login_handler.login():
                    self.logger.error("登录失败，无法继续")
                    return False
            else:
                self.logger.info("已经登录，跳过登录步骤")

            # 步骤2: 搜索并选择演出
            self.logger.info("步骤2: 搜索演出")
            if not self.ticket_selector.search_event(event_name):
                self.logger.error("搜索演出失败")
                return False

            if not self.ticket_selector.select_event_from_results(event_name):
                self.logger.error("从搜索结果中选择演出失败")
                return False

            # 步骤3: 选择场次和票价
            self.logger.info("步骤3: 选择场次和票价")
            session_index = ticket_config.get("session_index", 0)
            if not self.ticket_selector.select_session(session_index):
                self.logger.warning("选择场次失败，继续执行")

            price_index = ticket_config.get("price_index", 0)
            if not self.ticket_selector.select_price(price_index):
                self.logger.error("选择票价失败")
                return False

            # 步骤4: 选择票数
            ticket_num = ticket_config.get("ticket_num", 1)
            if not self.ticket_selector.select_ticket_quantity(ticket_num):
                self.logger.warning("选择票数失败，使用默认数量")

            # 步骤5: 开始抢票
            self.logger.info("步骤5: 开始抢票")
            self.logger.info("请确保已经到达开票时间，系统将持续尝试...")

            # 首次尝试点击购买按钮
            if not self.ticket_selector.click_buy_now():
                self.logger.warning("首次点击购买按钮失败，进入抢票模式")

            # 进入抢票循环
            success = self.ticket_grabber.start_grabbing()

            if success:
                self.logger.info("🎉 恭喜！抢票成功！")
                show_notification("抢票成功", f"成功抢到 {event_name} 的票！")
                return True
            else:
                self.logger.error("抢票失败")
                return False

        except Exception as e:
            self.logger.error(f"抢票流程异常: {e}")
            return False
        finally:
            # 保持App打开一段时间，让用户查看结果
            self.logger.info("抢票流程结束，App将保持打开状态...")

    def update_config(self, **kwargs) -> None:
        """更新配置"""
        try:
            if "user" in kwargs:
                user_info = kwargs["user"]
                self.config_manager.update_user_info(**user_info)

            if "ticket" in kwargs:
                ticket_info = kwargs["ticket"]
                self.config_manager.update_ticket_info(**ticket_info)

            # 重新加载配置
            self.config = self.config_manager.load_config()
            self.logger.info("配置已更新")

        except Exception as e:
            self.logger.error(f"更新配置失败: {e}")

    def test_device(self) -> bool:
        """测试设备连接功能"""
        try:
            self.logger.info("测试设备连接功能")
            app_package = self.config.get("mobile", {}).get("app_package", "cn.damai")

            # 测试启动App
            if self.driver.start_app(app_package):
                time.sleep(3)
                self.logger.info("设备连接和App启动测试成功")
                return True
            else:
                self.logger.error("App启动失败")
                return False

        except Exception as e:
            self.logger.error(f"设备测试失败: {e}")
            return False

    def cleanup(self) -> None:
        """清理资源"""
        try:
            if self.driver:
                self.driver.close_device()
            self.logger.info("资源清理完成")
        except Exception as e:
            if self.logger:
                self.logger.error(f"清理资源失败: {e}")

    def get_config_template(self) -> Dict[str, Any]:
        """获取配置模板"""
        return {
            "user": {
                "username": "你的大麦网用户名/手机号/邮箱",
                "password": "你的大麦网密码",
                "phone": "手机号码（用于订单）",
                "real_name": "真实姓名（实名制）",
                "id_card": "身份证号码（实名制）",
            },
            "ticket": {
                "event_name": "演出名称",
                "event_url": "演出详情页链接（App端暂不支持直接访问）",
                "session_index": 0,  # 场次索引，0表示第一场
                "price_index": 0,  # 票价索引，0表示第一个票价
                "ticket_num": 1,  # 购票数量
            },
            "mobile": {
                "device_id": "auto",  # 设备ID，auto表示自动连接
                "app_package": "cn.damai",  # 大麦App包名
                "implicit_wait": 10,
                "screenshot_on_error": True,
            },
            "retry": {
                "max_retry_times": 50,  # 最大重试次数
                "retry_interval": 0.5,  # 重试间隔（秒）
            },
            "notification": {
                "enable_sound": True,  # 启用声音通知
                "enable_popup": True,  # 启用弹窗通知
            },
        }
